/**
 * 路由
 * Copyright(C) 2018 liumurong
 */

import * as Router from 'koa-router'
import { ReceiverHelper } from './receive/receiverhelper';

// 处理路由
export let sliceRouter = new Router();

/**
 * 验证是否支持断点续传
 */
sliceRouter.all("/slice/health", async (ctx: Router.IRouterContext, next: () => Promise<any>) => {
    ctx.body = {
        stat: 0,
        msg: "OK"
    };
});

/**
 * 上传文件
 * @param hash          // 文件Hash
 * @param name          // 文件名称
 * @param index         // 块索引
 * @param slicecount    // 总块儿数
 * @param size          // 文件总大小
 * @param chunksize     // 块大小
 * @body  数据块
 */
sliceRouter.all("/slice/upload", async (ctx: Router.IRouterContext, next: () => Promise<any>) => {
    let { hash, name, index, slicecount, size, chunksize } = ctx.query;
    let data: Buffer = null;
    if (!hash) {
        ctx.body = { stat: 1, msg: "hash值不能为空" };
        return;
    }
    if (!name) {
        ctx.body = { stat: 2, msg: "name值不能为空" };
        return;
    }
    if (!index) {
        ctx.body = { stat: 3, msg: "index值不能为空" };
        return;
    }
    if (!slicecount) {
        ctx.body = { stat: 4, msg: "slicecount值不能为空" };
        return;
    }
    if (!size) {
        ctx.body = { stat: 5, msg: "size值不能为空" };
        return;
    }
    if (!chunksize) {
        ctx.body = { stat: 6, msg: "chunksize值不能为空" };
        return;
    }
    // 接收数据
    await new Promise((resolve, reject) => {
        ctx.req.on("data", (buf) => {
            data = data ? Buffer.concat([data, <Buffer>buf]) : <Buffer>buf;
        })
        ctx.req.on("error", () => {
            reject();
        })
        ctx.req.on("end", () => {
            resolve();
        })
    });
    // 保存
    await ReceiverHelper.instance.receiver.saveSlice({
        hash: hash,
        name: name,
        index: parseInt(index),
        slicecount: parseInt(slicecount),
        size: parseInt(size),
        chunksize: parseInt(chunksize),
        data: data
    });
    ctx.body = {
        stat: 0,
        msg: "ok"
    };
});

/**
 * 获取服务器上文件块的HASH值
 * @param hash 文件的HASH码。默认采用sha256算法生成
 * @param depth HASH深度
 * @param index 当前深度的索引
 */
sliceRouter.all("/slice/:hash/:depth/:index", async (ctx: Router.IRouterContext, next: () => Promise<any>) => {
    let { hash, depth, index } = ctx.params;
    let nodeHash = await ReceiverHelper.instance.receiver.getNodeHash(hash, depth, index);
    ctx.body = {
        stat: 0,
        msg: "OK",
        val: nodeHash
    }
});

/**
 * 获取已经上传的文件的片数
 */
sliceRouter.all("/slice/count/:hash", async (ctx: Router.IRouterContext, next: () => Promise<any>) => {
    const { hash } = ctx.params;
    if (!hash) {
        ctx.body = {
            stat: 1,
            msg:'无hash值'
        }
    }
    const uploadedCount = await ReceiverHelper.instance.receiver.getUploadedCount(hash);
    ctx.body = {
        stat: 0,
        msg: '成功',
        val: uploadedCount
    }
})